package parser;

import lexer.Lexer;

/**
 * BasicParser优化
 * Created by weijianyu on 2017/1/13.
 */
public class ImprovedParser {

    private Lexer lexer;
    private boolean isLegalStatement = true;

    public ImprovedParser(Lexer lexer) {
        this.lexer = lexer;
    }

    public void statements() {
        // statements -> expression; | expression; statements
        while (!lexer.match(Lexer.EOI)) {
            expression();
            if (lexer.match(Lexer.SEMI)) {
                lexer.advance();
            } else {
                isLegalStatement = false;
                System.out.println("line: " + lexer.yylineno + " Missing semicolon");
            }
        }

        if (isLegalStatement) {
            System.out.println("The statements is legal");
        }
    }

    private void expression() {
        // expression -> term expression'
        // expression' -> PLUS term expression' | 空
        term();
        while (lexer.match(Lexer.PLUS)) {
            lexer.advance();
            term();
        }

        if (lexer.match(Lexer.UNKNOWN_SYMBOL)) {
            isLegalStatement = false;
            System.out.println("unknow symbol: " + lexer.yytext);
        } else {
            //"空" 就是不再解析，直接返回
        }
    }

    private void term() {
        // term -> factor term'
        // term' -> TIMES factor term' | '空'
        factor();
        while (lexer.match(Lexer.TIMES)) {
            lexer.advance();
            factor();
        }

        if (lexer.match(Lexer.UNKNOWN_SYMBOL)) {
            isLegalStatement = false;
            System.out.println("unknow symbol: " + lexer.yytext);
        } else {
            //"空" 就是不再解析，直接返回
        }
    }

    private void factor() {
        // factor -> NUM_OR_ID | LP expression RP
        if (lexer.match(Lexer.NUM_OR_ID)) {
            lexer.advance();
        } else if (lexer.match(Lexer.LP)) {
            lexer.advance();
            expression();
            if (lexer.match(Lexer.RP)) {
                lexer.advance();
            } else {
                // 有左括号但没有右括号，错误
                isLegalStatement = false;
                System.out.println("line: " + lexer.yylineno + " Missing )");
            }
        } else {
            // 这里不是数字，解析出错
            isLegalStatement = false;
            System.out.println("illegal statements");
        }
    }

    public static void main(String[] args) {
        Lexer lexer = new Lexer();
        ImprovedParser improvedParser = new ImprovedParser(lexer);
        improvedParser.statements();
    }
}
